import React from 'react'
import {getGameLoginInfo, getMallHotReq, getMallListReq, getUserDetailReq, refreshTkReq} from "../../apis/goApis";
import {log} from "../../utils/commonfunc";
import bannerSrc from "../../res/images/web/mall/商城-顶部bg@2x.png"
import './mall.css'
import {Icon, Modal} from "antd-mobile";
import HeaderAvatar from "../my/components/MyHeader/HeaderAvatar/HeaderAvatar";
import beanSrc from "../../res/images/web/mall/应豆-白@2x.png"
import LocalStorageService from "../../utils/LocalStorageService";
import CustomBotton from "../../shared-components/CustomButton/CustomBotton";
import MallItemCard from "./mall-item-card/mall-item-card";
import adSrc from "../../res/images/web/mall/应豆商城小广告@2x.png"
import labaSrc from "../../res/images/web/mall/喇叭-中奖公告 大@2x.png"
import MallHotItemCard from "./mall-hot-item-card/mall-hot-item-card";
import hotSrc from '../../res/images/web/mall/hot@2x.png'
import ruleSrc from '../../res/images/web/mall/编组 12@2x.png'
import {test} from "../../utils/constants";
import {checkAndGoBack} from "../best-line-up/best-line-up";
export const searchParams = () => {
    const search = window.location.search
        .slice(1)
        .split('&')
        .map(keyValue => {
            return keyValue.split('=')
        })
        .reduce((acc, cur) => {
            if (cur[1]) {
                acc[cur[0]] = cur[1]
                return acc
            }
            return acc
        }, {})
    return search
}

export const pushWithSearch = (history, url, state = null) => {
    let end = url
    const search = searchParams()
    const entries = Object.entries(search)
    if (entries.length > 0) {
        end += '?'
        entries.map(([key, value], index) => {
            end += `${key}=${value}`
            if (index !== entries.length - 1) {
                end += '&'
            }
        })
    }
    if (state) {
        history.push(end, state,)
    } else {
        history.push(end)
    }

}

export const bindScrollEvent = (container, callback, gap = 0) => {
    const hei = container.scrollHeight
    const top = container.scrollTop
    const cHei = container.clientHeight
    const toBottom = (hei - cHei) - top
    if (toBottom <= gap) {
        callback()
    }
}

class Mall extends React.Component {

    constructor(props) {
        super(props)
        this.uid = LocalStorageService.get('userid')
        this.searchParams = searchParams()
        this.state = {
            bannerLoaded: false,
            list: [],
            hot: [],
            notice: [],
            noticeIndex: 1,
            p: 0,
            user: {
                name: '',
                icon: '',
                bean: '',
            },
            modal: {
                rule: false,
            }
        }
    }

    componentDidMount() {
        this.getUser()
            .then(() => this.hot())
            .then(() => this.all())
            .then(() => this.notice())
    }

    getUser = () => {

        const params = {
            uid: this.uid,
        }
        const search = this.searchParams
        if (search.uid) {
            params.uid = search.uid
        }
        return getUserDetailReq(params, false)
            .then(res => {
                const data = res.data.ok
                log(data)
                if (data) {
                    this.setState({
                        user: {
                            bean: data.Yd,
                            icon: data.Iconurl,
                            name: data.Nickname,
                        },
                    })
                }
            })

    }

    all = () => {
        const params = {
            p: this.state.p,
        }
        return getMallListReq(params)
            .then((res) => {
                const list = res.data.ok
                log(list)
                if (list) {
                    this.setState({
                        list: [...this.state.list, ...list,],
                    })
                }
            })
    }

    hot = () => {
        return getMallHotReq()
            .then(res => {
                const hot = res.data.ok
                if (hot) {
                    this.setState({
                        hot,
                    })
                }
            })
    }

    notice = () => {
        const notice = `
        战术后仰 刚刚兑换了 ipone12 Pro
        圣布托的鱼 刚刚兑换了 Apple Watch SE
        一脚定江山 刚刚兑换了 篮球
        Allen 刚刚兑换了球衣
        洛  刚刚兑换了10元话费充值卡
        Tabby 刚刚兑换了跳绳
        教练我想提足球 刚刚兑换了 ipone12 
        隔壁的姐姐 刚刚兑换了 AirPods
        19号技师  刚刚兑换了50元话费充值卡
        梅东  刚刚兑换了30元话费充值卡
        阿铲 刚刚兑换了球鞋
        德比的德比 刚刚兑换了双肩包
        童童爱足球 刚刚兑换了100元话费充值卡
        李先生  刚刚兑换了华为 mate40`
            .split('\n')
            .map(l => {
                const word = l.split(' ').filter(c => c !== '').join(' ')
                return word
            })
            .filter(line => line !== '')
        this.setState({
            notice,
        }, () => this.countNotice())
    }

    countNotice = () => {
        let next = this.state.noticeIndex + 1
        if (next === this.state.notice.length / 2) {
            next = 0
        }
        this.setState({
            noticeIndex: next,
        }, () => {
            setTimeout(() => this.countNotice(), 3000)
        })
    }

    callModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    cancelModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: false,
            }
        })
    }

    goToTask = () => {
        const params = {
            uid: this.uid,
            Gametype: 'task',
        }
        if (this.searchParams.uid) {
            params.uid = this.searchParams.uid
        }
        getGameLoginInfo(params)
            .then((res) => {
                const data = res.data.ok
                const end = data.gameUrl
                window.location = end
            })
    }

    onScroll = () => {
        const ctn = this.scrcollContainer
        bindScrollEvent(ctn, () => {
            this.setState({
                p: this.state.p + 1,
            }, () => this.all())
        }, 0)
    }

    render() {

        const user = this.state.user
        const list = this.state.list
        const hot = this.state.hot
        const notice = this.state.notice
        const noticeTranslateY = this.state.noticeIndex * (17 * 2 + 8)
        const webview = this.searchParams.webview === 'true'
        let goBackEnd = test ? 'http://123.207.85.242:8080/ren_wu' : 'http://www.youtoball.com:8080/ren_wu'


        let goBackIcon = <Icon
            type="left"
            size='lg'
            color='#fff'
            onClick={() => checkAndGoBack(this.props.history, './ren_wu')}
        />

        if (webview) {
            goBackIcon = <a href={goBackEnd}>
                <Icon type="left" size='lg' color='#fff'/>
            </a>
        }

        const history = this.props.history
        const loaded = this.state.bannerLoaded

        const bannerMainTemplate = <>
            <div className='mall-banner-tab-container flex-align-center fade-in'>
                <div className='mall-banner-tab flex-space-between-align-center'>
                    {goBackIcon}
                    <p>应豆商城</p>
                    <span
                        onClick={() => this.callModal('rule')}
                    >规则说明</span>
                </div>
            </div>
            <div className='mall-banner-user-container pd-12 flex-space-between-align-center fade-in'>
                <div
                    className='mall-banner-user flex-align-center flex-1'
                    // onClick={() => this.props.history.push('./my-bean')}
                    onClick={() => pushWithSearch(history,'./my-bean')}
                >
                    <HeaderAvatar avatarUrl={user.icon} width={40}/>
                    <p className='mall-banner-user-name'>{user.name}</p>
                    <img src={beanSrc} alt='' className='mall-banner-user-bean'/>
                    <p className='mall-banner-user-bean-count'>{user.bean}</p>
                    <Icon type="right" size='xxs' color='#fff'/>
                </div>
                <CustomBotton
                    extrastyle={{
                        width: '68px',
                        height: '28px',
                        letterSpacing: 0,
                        color: '#fff',
                        background: '#FFA500',
                        lineHeight: '28px',
                        fontSize: '14px',
                    }}
                    // onClick={() => this.props.history.push('./mall-record')}
                    onClick={() => pushWithSearch(history,'./mall-record')}
                >
                    兑换记录
                </CustomBotton>
            </div>
            <div className='mall-banner-notice-container fade-in'>
                <div className='mall-banner-notice flex-align-center'>
                    <img src={labaSrc} alt=''/>
                    <div className='mall-banner-notice-lines'>
                        {notice.map((line, index) => <p
                            key={index}
                            className='mall-banner-notice-line'
                            style={{
                                transform: `translateY(-${noticeTranslateY}px)`,
                            }}
                        >{line}</p>)}
                    </div>
                </div>
            </div>
        </>

        const taskTemplate = <div
            className='pd-l-r-12px fade-in'
        >
            {webview
                ? <a href={goBackEnd}>
                    <img src={adSrc} style={{width: '100%'}} alt=''/>
                </a>
                : <img src={adSrc} style={{width: '100%'}} alt='' onClick={() => this.goToTask()}/>
            }
        </div>
        const listTemplate = <div className='pd-12'>
            <p className='mall-title fade-in'>福利兑换</p>
            <div className='mall-items-container flex-space-between-align-center flex-wrap-container'>
                {list.map((mallItem, index) => <MallItemCard data={mallItem} key={index}/>)}
            </div>
        </div>

        const hotTemplate = <div className='pd-12 fade-in'>
            <div className='flex-align-center mg-b-8px'>
                <img src={hotSrc} style={{width: '16px', height: '16px', marginRight: '4px',}} alt=''/>
                <p className='mall-title' style={{marginBottom: 0,}}>热门兑换</p>
            </div>

            <div className='mall-hot-container flex-space-between-align-center'>
                {hot.map((mallItem, index) => <MallHotItemCard data={mallItem} key={index}/>)}
            </div>
        </div>

        return <>
            <Modal
                visible={this.state.modal.rule}
                onCancel={() => this.cancelModal('rule')}
                transparent
                className='rule-modal'
            >
                <div className='mall-rule-modal' onClick={() => this.cancelModal('rule')}>
                    <img alt='' src={ruleSrc}/>
                </div>
            </Modal>
            <div
                style={{
                    height: window.innerHeight,
                    width: window.innerWidth,
                    overflowY: 'scroll',
                }}
                onScroll={this.onScroll}
                ref={el => this.scrcollContainer = el}
            >
                <div className='mall-banner-container'>
                    <img
                        src={bannerSrc}
                        alt=''
                        className='mall-banner'
                        onLoad={() => {
                            this.setState({
                                bannerLoaded: true,
                            })
                        }}
                    />
                    {loaded && bannerMainTemplate}
                </div>
                {/*{loaded && taskTemplate}*/}
                {loaded && hotTemplate}
                {loaded && listTemplate}
            </div>
        </>
    }
}

export default Mall